<template>
  <div class="container">
    <el-row :gutter="0" style="margin-left: 0px; margin-right: 0px;">
      <el-col :span="8" style="padding-left: 0px; padding-right: 0px; border:3px solid #f3f3f3; border-radius: 10px;">
        <el-card style="width: 100%; min-height: 600px; color: #333">
          <div style="padding-bottom: 10px; border-bottom: 2px solid #303f9f; font-size: 16px; font-weight: bold">
            在线用户<span style="font-size: 12px">（点击按钮开始聊天）</span>
          </div>
          <div v-if="users.length > 0">
            <div style="padding: 10px 0" v-for="user in users" :key="user.username">
              <span style="font-size: 14px">{{ user.username }}</span>
              <el-button type="primary" size="mini" style="margin-left: 10px" @click="selectUser(user)">
                聊天
              </el-button>
              <span style="font-size: 12px; color: limegreen; margin-left: 5px" v-if="user.username === chatUser">正在聊天...</span>
            </div>
          </div>
          <div v-else>
            <p style="font-size: 14px">暂无在线用户</p>
          </div>
        </el-card>
      </el-col>

      <el-col :span="16" style="padding-left: 10px; padding-right: 10px;">
        <div style="width: 100%; margin: 0 0 0 0; background-color: white; border-radius: 10px; box-shadow: 0 0 10px #ccc">
          <div style="text-align: center; line-height: 50px; font-size: 18px; font-weight: bold">
            远程医疗服务咨询({{ chatUser || '请选择聊天对象' }})
          </div>
          <div style="height: 350px; overflow: auto; border-top: 2px solid #303f9f" v-html="content"></div>
          <div style="height: 200px">
            <textarea v-model="text" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #303f9f; border-bottom: 1px solid #303f9f; outline: none; font-size: 14px; line-height: 1.5"></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import request from "@/utils/request";
let socket;

export default {
  name: "Im",
  data() {
    return {
      circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      user: {},
      isCollapse: false,
      users: [],
      chatUser: '',
      text: "",
      messages: [],
      content: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    send() {
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"});
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"});
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          let message = {from: this.user.username, to: this.chatUser, text: this.text};
          socket.send(JSON.stringify(message));
          this.messages.push({user: this.user.username, text: this.text});
          this.createContent(null, this.user, this.text);
          this.text = '';
        }
      }
    },
    createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
            "    <div class=\"tip left\">" + text + "</div>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-2\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "</div>";
      } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
        html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
            "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
            "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
            "    <img src=\"https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png\" style=\"object-fit: cover;\">\n" +
            "  </span>\n" +
            "  </div>\n" +
            "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
            "    <div class=\"tip right\">" + text + "</div>\n" +
            "  </div>\n" +
            "</div>";
      }
      console.log(html)
      this.content += html;
    },
    init() {
      this.user = localStorage.getItem("username") ? JSON.parse(localStorage.getItem("username")) : {}
      let username = this.user;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8080/ws/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        socket = new WebSocket(socketUrl);

        socket.onopen = () => {
          console.log("websocket已打开");
        };

        socket.onmessage = (msg) => {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data);
          if (data.users) {
            this.users = data.users.filter(user => user.username !== username);
            console.log("在线用户:", this.users); // 调试信息
          } else {
            if (data.from === this.chatUser) {
              this.messages.push(data);
              this.createContent(data.from, null, data.text);
            }
          }
        };

        socket.onclose = () => {
          console.log("websocket已关闭");
        };

        socket.onerror = () => {
          console.log("websocket发生了错误");
        };
      }
    },
    selectUser(user) {
      this.chatUser = user.username;
      this.content = ''; // 清空聊天记录
      this.messages = []; // 清空消息列表
      console.log("Selected user:", this.chatUser); // 调试信息
    }
  }
}
</script>

<style>
body {
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}
.container {
  max-width: 1200px; /* 设置最大宽度 */
  margin: 0 auto; /* 居中显示 */
  padding: 20px; /* 可选：添加一些内边距 */
}

.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block;
  font-size: 14px;
  line-height: 1.5;
}

.right {
  background-color: deepskyblue;
}

.left {
  background-color: #6c757d;
}
</style>